<%@ page language="java" pageEncoding="UTF-8"%>
<%@ include file="/mb/jsp/common.jsp" %>
<!doctype html>
<html>
<head>
    <title>k line painter</title>
    <script src="mb/libs/loading.js" type="text/javascript" ></script>
    <script src="mb/libs/util.js" type="text/javascript" ></script>
    <script src="mb/libs/absPainter.js" type="text/javascript" ></script>
    <script src="mb/libs/ajax.js" type="text/javascript" ></script>
    <script src="mb/libs/crossLines.js" type="text/javascript" ></script>
    <script src="mb/libs/axis-x.js" type="text/javascript" ></script>
    <script src="mb/libs/tip.js" type="text/javascript" ></script>
    <script src="mb/libs/linepainter.js" type="text/javascript" ></script>
    <script src="mb/libs/volumePainter.js" type="text/javascript" ></script>
    <script src="mb/libs/axis-y.js" type="text/javascript" ></script>
    <!-- 手机上用这个 -->
    <script src="mb/libs/chartEventHelper.js?a2" type="text/javascript" ></script> 
    <script type="text/javascript" src="mb/libs/controller.js" ></script>
    <!-- 原始数据 -->
    <script type="text/javascript" src="mb/libs/k-Day-data.js"></script>  
       
    <script type="text/javascript">
    
       	
    var kl;
    var Kdata;
    
    var Kdata0;
    var Kdata1;
    var Kdata2;
    var Kdata3;
    var Kdata4;
    var Kdata5;
    
    var painter;// = new Painter('canvasKL', kl, data);
    
    var K_type=5; //0：日线 1:60分钟 2:30分钟 3:15分钟 4:5分钟 5:1分钟   6分时 
    var endDataDtime=0;//
    
    var endDataDtime0=0;//
    var endDataDtime1=0;//
    var endDataDtime2=0;//
    var endDataDtime3=0;//
    var endDataDtime4=0;//
    var endDataDtime5=0;//
    
    
    $().ready(function() {   
    	drawKL();
	    loadBuyUserList();
	    setInterval(loadBuyUserList,7000);
  	});
  	
  	function forPaient(type)
  	{
  		K_type=type;
  		Kdata.isinit=true;
  		endDataDtime=0;
  		loadBuyUserList();
  	}
  	
  	
  	//取支持数据 k线类型
	function loadBuyUserList()
	{
/* 		switch(K_type)
		{
			case 0:
			endDataDtime=endDataDtime0;
			Kdata=Kdata0;
			break;
			case 1:
			endDataDtime=endDataDtime1;
			Kdata=Kdata1;
			break;
			case 2:
			endDataDtime=endDataDtime2;
			Kdata=Kdata2;
			break;
			case 3:
			endDataDtime=endDataDtime3;
			Kdata=Kdata3;
			break;
			case 4:
			endDataDtime=endDataDtime4;
			Kdata=Kdata4;
			break;
			case 5:
			endDataDtime=endDataDtime5;
			Kdata=Kdata5;
			break;		
		
		} */
		
		
		
		
	    //var projectidV=$("#P_projectid").html();
		$.ajax({
	            url: "LoginServlet",
	            //data: JSON.stringify({m:281,type:KType,endtime:endDataDtime}),
	            data: JSON.stringify({m:282,type:K_type,timeid:endDataDtime}),
	            type: 'post',
	            dataType: 'json',
	            contentType:"application/json;charset=utf-8",
	            success: function (data) {
	   	           if(data['state']==1)
		           {
		           		switch(data['type'])
						{
						
						
		           		}
		           
		           		endDataDtime=data.obj.timeid*1;
		           		if(data.obj!=null && data.obj.kdatalist!=null && data.obj.kdatalist.length>0){
			                if(Kdata.isinit) //初始状态
			                {
			                	Kdata.high=data.obj.high;
			                	Kdata.low=data.obj.low;
			                	Kdata.isinit=false;
			                	Kdata.ks=data.obj.kdatalist;
			                	drawKL();
			                }
			                else  //追加数据
			                {
			                	Kdata.high=data.obj.high;
			                	Kdata.low=data.obj.low;
			                	Kdata.isinit=false;
			                	var lenK=Kdata.ks.length;
			                	var lenO=data.obj.kdatalist.length;
			                	
			                	if(lenK<=lenO)
			                	{
			                		Kdata.ks=data.obj.kdatalist;
			                	}
			                	else
			                	{ 
			                	   	 for(var tm=lenK;tm>0;tm--)
			                		 {
			                		   	if(Kdata.ks[tm-1].quoteTime*1.0==data.obj.kdatalist[0].quoteTime*1.0)
			                		   	{
			                		   		var dd=Kdata.ks.splice(tm-1,lenK-tm+1);
			                		   		break;
				                		}
			                		 }
			                	    $.each(data.obj.kdatalist, function(index, objVal) 
			                		{
			                			Kdata.ks.push(objVal);
			                		});
			                	}
			                	
			                	if(painter.maxTime<=endDataDtime)
			                	{drawKL(painter.dataRanges);}
			                }
			                
		                }
		           }
		           else
		           {
		           		Kdata.isinit=true;
		           		endDataDtime=0;
		           }
		        },
		        error: function (data) {
		           
                 	return false;
                },
         });
    }
  	
    
        //时间格式由在来的20161026 改为201610261025 
        function convertDate(val, withWeek) {
        
        	var year = Math.ceil(val / 100000000) - 1;
         	var month = (Math.ceil(val / 1000000) - 1) % 100;
            var day = (Math.ceil(val / 10000) - 1) % 100;
            
            var i=Math.ceil(val % 100);
            if(i==0)
            {
            	var hour = (val/100) % 100;
            }
            else
            {
            	var hour = (Math.ceil(val / 100) - 1) % 100;
            }
             
            
            var minute = val % 100;  
            
            //var d = new Date();
            //d.setYear(year);
            //d.setMonth(month - 1);
            //d.setDate(day);
            if (month < 10) month = '0' + month;
            if (day < 10) day = '0' + day;
            if (hour < 10) hour = '0' + hour;
            if (minute < 10) minute = '0' + minute;
           
            //if (withWeek) {
            //    var weekNames = ['日', '一', '二', '三', '四', '五', '六'];
            //    return year + '-' + month + '-' + day + '(星期' + weekNames[d.getDay()] + ')';
            //}
            //else {
                return year + '-' + month + '-' + day+' '+hour+':'+minute;
            //}
        }
        function calcMAPrices(ks, startIndex, count, daysCn) {
            var result = new Array();
            for (var i = startIndex; i < startIndex + count; i++) {
                var startCalcIndex = i - daysCn + 1;
                if (startCalcIndex < 0) {
                    result.push(false);
                    continue;
                }
                var sum = 0;
                for (var k = startCalcIndex; k <= i; k++) {
                    sum += ks[k].close*1.0;
                }
                var val = sum / daysCn;
                result.push(val);
            }
            return result;
        }

        var timer = {
            start:function(step){this.startTime = new Date();this.stepName = step;},
            stop:function(){
                var timeSpan = new Date().getTime() - this.startTime.getTime();
                setDebugMsg(this.stepName + '耗时' + timeSpan+'ms');
            }
        };

        function kLine(options) {
            this.options = options;
            this.dataRanges = null;
        }

        kLine.prototype = {
            initialize: function (painter) {
                painter.klOptions = this.options;
                painter.implement = this;
            },
            start: function () {
                //timer.start('start');
                var canvas = this.canvas;
                var ctx = this.ctx;
                this.painting = true;
                var options = this.klOptions;
                var clearPart = { width: canvas.width, height: options.priceLine.region.y+10 };
                
                
                ctx.clearRect(0, 0, clearPart.width, clearPart.height);
									
                ctx.save();
                window.riseColor = options.riseColor;
                window.fallColor = options.fallColor;
                window.normalColor = options.normalColor;
                if (options.backgroundColor ) {
                    ctx.beginPath();
                    ctx.fillStyle = options.backgroundColor;
                    ctx.rect(0, 0, clearPart.width, clearPart.height);
                    ctx.fill();
                    //ctx.closePath();
                    this.drawnBackground = true;
                }
                ctx.translate(options.region.x, options.region.y);
                ctx.strokeStyle = options.borderColor;
                ctx.beginPath();
                ctx.rect(0, 0, options.region.width, options.region.height);
                ctx.stroke();
                //画水平底纹线
                var spaceHeight = options.region.height / (options.horizontalLineCount + 1);
                for (var i = 1; i <= options.horizontalLineCount; i++) {
                    var y = spaceHeight * i;
                    if (y * 10 % 10 == 0) y += .5;
                    this.drawHLine(options.splitLineColor, 0, y, options.region.width, 1, options.lineStyle);
                }
                //画垂直底纹线
                var spaceWidth = options.region.width / (options.verticalLineCount + 1);
                for (var i = 1; i <= options.verticalLineCount; i++) {
                    var w = spaceWidth * i;
                    if (w * 10 % 10 == 0) w += .5;
                    this.drawVLine(options.splitLineColor, w, 0, options.region.height, 1, options.lineStyle);
                }
                //timer.stop();
            },
            end: function () {
                this.ctx.restore();
                var me = this;
                var options = me.klOptions;
                var region = options.region;
                var volumeRegion = options.volume.region;

                function getIndex(x) {
                    x -= region.x;
                    var index = Math.ceil(x / (me.klOptions.spaceWidth + me.klOptions.barWidth)) - 1;
                    var count = me.toIndex - me.startIndex + 1;
                    if (index >= count) index = count - 1;
                    return index;
                }
                function getX(x) {
                    var index = getIndex(x);
                    return region.x + me.klOptions.spaceWidth * (index + 1) + me.klOptions.barWidth * index + me.klOptions.barWidth * .5;
                }
                function getPriceColor(ki, price) {
                    if (price > ki.preClose) {
                        return riseColor;
                    } else if (price < ki.preClose) {
                        return fallColor;
                    } else {
                        return normalColor;
                    }
                }
                function getTipHtml(x) {
                    var index = me.startIndex + getIndex(x);
                    if (index >= me.data.ks.length) index = me.data.ks.length - 1;
                    if (index < 0) index = 0;
                    var ki = me.data.ks[index];
                    var tipHtml = '<div><b>' + convertDate(ki.quoteTime) + '</b></div>' +
                    '昨收价：<font color="' + getPriceColor(ki, ki.preClose) + '">' + toMoney(ki.preClose) + '</font><br/>' +
                    '开盘价：<font color="' + getPriceColor(ki, ki.open) + '">' + toMoney(ki.open) + '</font><br/>' +
                    '最高价：<font color="' + getPriceColor(ki, ki.high) + '">' + toMoney(ki.high) + '</font><br/>' +
                    '最低价：<font color="' + getPriceColor(ki, ki.low) + '">' + toMoney(ki.low) + '</font><br/>' +
                   '收盘价：<font color="' + getPriceColor(ki, ki.close) + '">' + toMoney(ki.close) + '</font><br/>' +
                    '成交量：' + bigNumberToText(ki.volume / 100) + '手<br/>' +
                    '成交额：' + bigNumberToText(ki.amount);
                    return tipHtml;
                }

                function getEventOffsetPosition(ev){                    
                    var offset = isTouchDevice()
                        ? setTouchEventOffsetPosition(ev, getPageCoord(me.canvas))
                        : getOffset(ev);
                    return offset;
                }
                
                var controllerEvents = {
                    onStart:function(ev){
                        ev = ev || event;
                        var offset = getEventOffsetPosition(ev);
                        me.controllerStartOffset = offset;
                        me.controllerStartRange = me.dataRanges;
                    },
                    onEnd:function(ev){
                        me.controllerStartOffset = null;
                        me.controllerStartRange = null;
                    },
                    onMove:function(ev){
                        if(!me.controllerStartOffset) return;
                        ev = ev || event;
                        var offset = getEventOffsetPosition(ev);
                        var moveX = offset.offsetX - me.controllerStartOffset.offsetX;
                        var currentRange = me.controllerStartRange;/*0-100*/
                        var regionWidth = region.width;
                        var moveValue =0- (moveX/regionWidth)*(currentRange.to-currentRange.start);
                        var start = currentRange.start+moveValue;
                        var to = currentRange.to + moveValue;
                        if(start<0) {
                            start = 0;
                            to = start + (currentRange.to-currentRange.start);
                        }
                        else{
                            if(to > 100){
                                to = 100;
                                start = to-(currentRange.to-currentRange.start);
                            }
                        }                        
                        var changeToValue = {left:start,right:to};
                        if(!me.painting) drawKL({ start: changeToValue.left, to: changeToValue.right });
                    },
                    onMouseWheel:function(ev)
                    {
                        
                    	//ev = ev || event;
                    	var currentRange = me.dataRanges;
                    	var start=0;
                    	var to=0;
                    	var flag=0;
                    	
                    	if(ev.wheelDelta){//IE/Opera/Chrome 
					        flag=ev.wheelDelta; 
					    }else if(ev.detail){//Firefox 
					        flag=ev.detail; 
					    }
					    if (flag < 0) //放大
                    	{
                    		start=currentRange.start+0.2;
                    		to=currentRange.to;
                    	}
                    	else  //放小
                    	{

                    		start=currentRange.start-0.2;
                    		to=currentRange.to;
                    	}
                    	
                    	if(start<0) {
                            start = 0;
                            to = start + (currentRange.to-currentRange.start);
                        }
                        else if(start>=100)
                        {
                        	start=start-0.2;
                        }
                        else{
                            if(to > 100){
                                to = 100;
                                start = to-(currentRange.to-currentRange.start);
                            }
                        } 
                        if(start>=to)
                        {
                        	start=start-0.2;
                        	to=to+0.2;
                        }
                    	
                    	var changeToValue = {left:start,right:to};
                    	if(!me.painting) drawKL({ start: changeToValue.left, to: changeToValue.right });
                    	
                    }
                };

                /*
                	当touchstart时的位置在K线柱附近时表示要显示柱的描述信息框；否则则要控制K线的范围
                */
                var fingerSize = {width:30,height:20};
                function shouldDoControllerEvent(ev,evtType){ 
                    if(evtType == undefined) return true;
                    if(typeof me.shouldController == 'undefined') me.shouldController = true;
                    if(evtType == 'touchstart'){
                        var offset = getEventOffsetPosition(ev);
                        var showTip=false;

                        var x = offset.offsetX;
                        x -= region.x;
                        var index = Math.ceil(x / (me.klOptions.spaceWidth + me.klOptions.barWidth)) - 1;

                        var indexRange = Math.ceil(fingerSize.width / (me.klOptions.spaceWidth + me.klOptions.barWidth))+1;

                        var indexStart = Math.max(0,index - indexRange/2);
                        var indexTo = Math.min(me.filteredData.length-1,index+indexRange/2);
                        var yMin=999999;
                        var yMax=-1;
                        for(index = indexStart;index<=indexTo;index++){
                            var dataAtIndex = me.filteredData[index];
                            var yTop = region.y+ (me.high - dataAtIndex.high) * region.height / (me.high - me.low) - fingerSize.height;
                            var yBottom = region.y+(me.high - dataAtIndex.low) * region.height / (me.high - me.low) + fingerSize.height;
                            yMin = Math.min(yTop,yMin);
                            yMax = Math.max(yBottom,yMax);
                        }
                        showTip = offset.offsetY >= yMin && offset.offsetY <= yMax;
                        setDebugMsg('yMin='+yMin + ',yMax=' + yMax + ',offsetY='+offset.offsetY+',showTip=' + showTip);
                        me.shouldController = !showTip;
                        
                    }
                    //setDebugMsg('shouldController=' + me.shouldController);
                    return me.shouldController;
                }

                if(!me.crossLineAndTipMgrInstance){
                    me.crossLineAndTipMgrInstance = new crossLinesAndTipMgr(me.canvas, {
                        getCrossPoint: function (ev) { return { x: getX(ev.offsetX), y: ev.offsetY }; },
                        triggerEventRanges: { x: region.x, y: region.y + 1, width: region.width, height: volumeRegion.y + volumeRegion.height - region.y },
                        tipOptions: {
                            getTipHtml: function (ev) { return getTipHtml(ev.offsetX); },
                            size:{width:120,height:150},
                            position:{x:false,y:region.y+(region.height-150)/3}, //position中的值是相对于canvas的左上角的
                            opacity:80,
                            cssClass:'',
                            offsetToPoint:30
                        },
                        crossLineOptions: {
                            color: 'black'
                        },
                        shouldDoControllerEvent:shouldDoControllerEvent,
                        controllerEvents:controllerEvents
                    });
                    me.crossLineAndTipMgrInstance.addCrossLinesAndTipEvents();
                }
                else {
                    me.crossLineAndTipMgrInstance.updateOptions({
                            getCrossPoint: function (ev) { return { x: getX(ev.offsetX), y: ev.offsetY }; },
                            triggerEventRanges: { x: region.x, y: region.y + 1, width: region.width, height: volumeRegion.y + volumeRegion.height - region.y },
                            tipOptions: {
                                getTipHtml: function (ev) { return getTipHtml(ev.offsetX); },
                                size:{width:120,height:150},
                                position:{x:false,y:region.y+(region.height-150)/3}, //position中的值是相对于canvas的左上角的
                                opacity:80,
                                cssClass:'',
                                offsetToPoint:30
                            },
                            crossLineOptions: {
                                color: 'black'
                            },
                            shouldDoControllerEvent:shouldDoControllerEvent,
                            controllerEvents:controllerEvents
                        });
                       
                }
                if (!me.addOrentationChangedEvent) {
                    me.addOrentationChangedEvent = true;

                    addEvent(window, 'orientationchange', function (ev) {
                        me.requestController = true;
                        me.implement.onOrentationChanged.call(me);
                    });
                }

                me.painting = false;
            },
            paintItems: function () {
                var options = this.klOptions;
                var region = options.region;
                var maxDataLength = this.data.ks.length;
                var needCalcSpaceAndBarWidth = true;
                if (this.dataRanges == null) {
                    //计算dataRanges
                    var dataCount = Math.ceil(region.width / (options.spaceWidth + options.barWidth))-1;
                    if (dataCount > maxDataLength) dataCount = maxDataLength;
                    this.dataRanges = {
                        start: 100 * (this.data.ks.length - dataCount) / this.data.ks.length,
                        to: 100
                    };

                    needCalcSpaceAndBarWidth = false;
                }
                var dataRanges = this.dataRanges;
                var startIndex = Math.ceil(dataRanges.start / 100 * maxDataLength);
                var toIndex = Math.ceil(dataRanges.to / 100 * maxDataLength) + 1;
                if (toIndex == maxDataLength) toIndex = maxDataLength - 1;
                this.startIndex = startIndex;
                this.toIndex = toIndex;
                var itemsCount = toIndex - startIndex + 1;
                if (needCalcSpaceAndBarWidth) { 
                    //重新计算spaceWidth和barWidth属性
                    function isOptionsOK() { return (options.spaceWidth + options.barWidth) * itemsCount <= region.width; }
                    var spaceWidth, barWidth;
                    
                    var barWidthAndspaceWidth=(1.0*region.width)/(1.0*itemsCount);
			        barWidth=Math.ceil(barWidthAndspaceWidth/2);
			        spaceWidth=barWidthAndspaceWidth-barWidth;
                    /* 
                    if (isOptionsOK()) {
                    
 			             var barWidthAndspaceWidth=(1.0*region.width)/(1.0*itemsCount);
			             var barWidth=Math.ceil(barWidthAndspaceWidth/2);
			             var spaceWidth=barWidthAndspaceWidth-barWidth;
                    
                        //柱足够细了
                        spaceWidth = 1;
                        barWidth = (region.width - spaceWidth * itemsCount) / itemsCount;
                        if (barWidth > 4) {
                            spaceWidth = 2;
                            barWidth = ((region.width - spaceWidth * itemsCount) / itemsCount);
                        }
                    } else {
                        spaceWidth = 1;
                        barWidth = (region.width - spaceWidth * itemsCount) / itemsCount;
                        if (barWidth <= 2) {
                            spaceWidth = 0;
                            barWidth = (region.width - spaceWidth * itemsCount) / itemsCount;
                        } else if (barWidth > 4) {
                            spaceWidth = 2;
                            barWidth = ((region.width - spaceWidth * itemsCount) / itemsCount);
                        }
                    } */

                    options.barWidth = barWidth;
                    options.spaceWidth = spaceWidth;
                }

                var filteredData = [];
                for (var i = startIndex; i <= toIndex && i < maxDataLength; i++) {
                    filteredData.push(this.data.ks[i]);
                }
                var high, low;
                filteredData.each(function (val, a, i) {
                    if (i == 0) { high = val.high; low = val.low; }
                    else { high = Math.max(val.high, high); low = Math.min(low, val.low); }
                });

                this.high = high;
                this.low = low;
                var ctx = this.ctx;
                var me = this;
                //timer.start('paintItems:移动均线');
                //画移动平均线
                this.implement.paintMAs.call(this, filteredData, getY);
                //timer.stop();
                //timer.start('paintItems:画柱');
                function getY(price) { return (me.high - price) * region.height / (me.high - me.low); }
                function getCandleLineX(i) { var result = i * (options.spaceWidth + options.barWidth) + (options.spaceWidth + options.barWidth) * .5; if (result * 10 % 10 == 0) result += .5; return result; }

                var currentX = 0;
                var needCandleRect = options.barWidth > 1.5;
                var drawCandle = function (ki, a, i) {
                    var isRise = ki.close > ki.open;
                    var color = isRise ? riseColor : fallColor;

                    var lineX = getCandleLineX(i);
                    if (currentX == 0) currentX = lineX;
                    else {
                        if (lineX - currentX < 1) return;
                    }
                    currentX = lineX;
                    var topY = getY(ki.high);
                    var bottomY = getY(ki.low);
                    if (needCandleRect) {
                        ctx.fillStyle = color;
                        ctx.strokeStyle = color;
                        var candleY, candleHeight;
                        if (isRise) {
                            candleY = getY(ki.close);
                            candleHeight = getY(ki.open) - candleY;
                        } else {
                            candleY = getY(ki.open);
                            candleHeight = getY(ki.close) - candleY;
                        }

                        //画线
                        ctx.beginPath();
                        ctx.moveTo(lineX, topY);
                        ctx.lineTo(lineX, bottomY);
                        ctx.stroke();

                        var candleX = lineX - options.barWidth / 2;
                        ctx.beginPath();
                        ctx.fillRect(candleX, candleY, options.barWidth, candleHeight);
                    } else {
                        ctx.strokeStyle = color;
                        //画线
                        ctx.beginPath();
                        ctx.moveTo(lineX, topY);
                        ctx.lineTo(lineX, bottomY);
                        ctx.stroke();
                    }

                };
                //画蜡烛
                filteredData.each(drawCandle);
                this.filteredData = filteredData;
                //timer.stop();
                //timer.start('paintItems:纵轴');
                
                
                
                var yAxisOptions = options.yAxis;
                yAxisOptions.region = yAxisOptions.region || { x: 0 - region.x, y: 0 - 3, height: region.height, width: region.x - 3 };
                //画y轴
                var yAxisImp = new yAxis(yAxisOptions);
                var yPainter = new Painter(
                    this.canvas.id,
                    yAxisImp,
                    calcAxisValues(high, low, (options.horizontalLineCount + 2))
                );
                yPainter.paint();
                //timer.stop();
                //timer.start('paintItems:横轴');
                //画X轴
                var xAxisOptions = options.xAxis;
                xAxisOptions.region = { x: 0, y: region.height + 2, width: region.width, height: 20 };
                var xAxisImp = new xAxis(xAxisOptions);
                var xScalers = [];
                
                var stepLength = filteredData.length / (options.xAxis.scalerCount - 1);
  /*               if (stepLength < 1) {
                    options.xAxis.scalerCount = filteredData.length;
                    stepLength = 1;
                } */
                
                var subStartIndex=0;
                var subEndIndex=0;
                switch(K_type)
                {
                	  case 0://日线
		                	subStartIndex=5;
		                	subEndIndex=5;
		                	break;
		              case 1://60分钟
  		              case 2://30分钟
  		              case 3://15分钟
		              case 4://5分钟
		              case 5://1分钟
		               	  	subStartIndex=11;
		                	subEndIndex=5;
		                	break;		                	   		                	              	
                }
                
                
                //时间格式由在来的20161026 改为201610261025
                xScalers.push(convertDate(filteredData[0].quoteTime, false).substr(subStartIndex,subEndIndex));
                for (var i = 1; i < options.xAxis.scalerCount; i++) {
                    var index = Math.ceil(i * stepLength);
                    if (index >= filteredData.length) index = filteredData.length - 1;
                    var quoteTime = convertDate(filteredData[index].quoteTime, false);
                    
                    //2016-10-26  改为2016-10-26 10:25
                    quoteTime = quoteTime.substr(subStartIndex,subEndIndex); //日线 显示10-26  分钟线显示 10:25
                    xScalers.push(quoteTime);
                    me.maxTime=filteredData[index].quoteTime;
                    
                }
 
                var xPainter = new Painter(this.canvas.id, xAxisImp, xScalers);
                xPainter.paint();
               // timer.stop();

                //timer.start('volume');
                //画量
                this.implement.paintVolume.call(this, filteredData);
                //timer.stop();
                //画价格线                
                //this.implement.paintPriceLine.call(this);
            },
            paintPriceLine: function () {
                if (this.hasPaintPriceLine) return;
                this.hasPaintPriceLine = true;
                var ctx = this.ctx;
                var options = this.klOptions.priceLine;
                var region = options.region;
                ctx.save();
                ctx.translate(region.x, region.y);

                ctx.clearRect(0 - region.x, 0, this.canvas.width, region.height);
                //画水平底纹线
                var spaceHeight = region.height / (options.horizontalLineCount + 1);
                for (var i = 1; i <= options.horizontalLineCount; i++) {
                    var y = spaceHeight * i;
                    if (y * 10 % 10 == 0) y += .5;
                    this.drawHLine(options.splitLineColor, 0, y, region.width, 1, options.lineStyle);
                }
                //画垂直底纹线
                var spaceWidth = region.width / (options.verticalLineCount + 1);
                for (var i = 1; i <= options.verticalLineCount; i++) {
                    var w = spaceWidth * i;
                    if (w * 10 % 10 == 0) w += .5;
                    this.drawVLine(options.splitLineColor, w, 0, region.height, 1, options.lineStyle);
                }
                var ks = this.data.ks;

                var ksLength = ks.length;
                var priceRange;
                ks.each(function (val, arr, i) {
                    if (i == 0) { priceRange = { high: val.high, low: val.low }; }
                    else {
                        priceRange.high = Math.max(priceRange.high, val.close);
                        priceRange.low = Math.min(priceRange.low, val.close);
                    }
                });
                if (priceRange.low > 1) priceRange.low -= 1;
                function getRangeX(i) { return i * region.width / ksLength; }
                function getRangeY(val) { return (priceRange.high - val) * region.height / (priceRange.high - priceRange.low); }
                var currentX = 0;
                ks.each(function (val, arr, i) {
                    var x = getRangeX(i);
                    if (currentX == 0) currentX = x;
                    else {
                        if (x - currentX < 1) return;
                    }
                    currentX = x;
                    var y = getRangeY(val.close);
                    if (i == 0) {
                        ctx.beginPath();
                        ctx.moveTo(x, y);
                    } else {
                        ctx.lineTo(x, y);
                    }
                });
                ctx.strokeStype = options.borderColor;
                ctx.stroke();
                ctx.lineTo(region.width, region.height);
                ctx.lineTo(0, region.height);
                ctx.closePath();
                ctx.fillStyle = options.fillColor;
                ctx.globalAlpha = options.alpha;
                ctx.fill();
                ctx.globalAlpha = 1;
                var yAxisOptions = options.yAxis;
                yAxisOptions.region = yAxisOptions.region || { x: 0 - region.x, y: 0 - 3, height: region.height, width: region.x - 3 };
                //画y轴
                var yAxisImp = new yAxis(yAxisOptions);
                var yPainter = new Painter(
                    this.canvas.id,
                    yAxisImp,
                    calcAxisValues(priceRange.high, priceRange.low, (options.horizontalLineCount + 2))
                );

                yPainter.paint();
                ctx.restore();
            },
            paintMAs: function (filteredData, funcGetY) {
                var ctx = this.ctx;
                var options = this.klOptions;
                var MAs = options.MAs;
                var me = this;
                MAs.each(function (val, arr, index) {
                    var MA = calcMAPrices(me.data.ks, me.startIndex, filteredData.length, val.daysCount);
                    val.values = MA;
                    MA.each(function (val, arr, i) {
                        if (val) {
                            me.high = Math.max(me.high, val);
                            me.low = Math.min(me.low, val);
                        }
                    });
                });

                MAs.each(function (val, arr, index) {
                    var MA = val.values;
                    ctx.strokeStyle = val.color;
                    ctx.beginPath();
                    var currentX = 0;
                    MA.each(function (val, arr, i) {
                        var x = i * (options.spaceWidth + options.barWidth) + (options.spaceWidth + options.barWidth) * .5;
                        
                        if (!val) return;
                        var y = funcGetY(val);
                        if (y && i==0) {
                            ctx.moveTo(x, y);
                        } else {
                            ctx.lineTo(x, y);
                        }
                    });
                    ctx.stroke();
                });
            },
            paintVolume: function (filteredData) { 
                var ctx = this.ctx;
                var options = this.klOptions;
                //画量线
                var volumeOptions = options.volume;
                var volumeRegion = volumeOptions.region;
                ctx.restore();
                ctx.save();
                ctx.translate(volumeRegion.x, volumeRegion.y);
                ctx.globalAlpha = 1;
                //画水平底纹线
                var spaceHeight = volumeRegion.height / (volumeOptions.horizontalLineCount + 1);
                for (var i = 1; i <= volumeOptions.horizontalLineCount; i++) {
                    var y = spaceHeight * i;
                    if (y * 10 % 10 == 0) y += .5;
                    this.drawHLine(options.splitLineColor, 0, y, options.region.width, 1, options.lineStyle);
                }
                //画垂直底纹线
                var spaceWidth = options.region.width / (options.verticalLineCount + 1);
                for (var i = 1; i <= options.verticalLineCount; i++) {
                    var w = spaceWidth * i;
                    if (w * 10 % 10 == 0) w += .5;
                    this.drawVLine(options.splitLineColor, w, 0, volumeRegion.height, 1, options.lineStyle);
                }

                ctx.strokeStyle = options.borderColor;
                ctx.beginPath();
                ctx.rect(0, 0, volumeRegion.width, volumeRegion.height);
                ctx.stroke();
                //drawLines(ctx, [{ direction: 'H', position: .50, color: 'lightgray'}]);
                var maxVolume = 0;

                filteredData.each(function (val, arr, i) {
                    maxVolume = Math.max(maxVolume, val.volume);
                });
                maxVolume *= 1.05;
                function getVolumeY(v) { return volumeRegion.height - volumeRegion.height / maxVolume * v; }
                function getVolumeX(i) { return i * (options.spaceWidth + options.barWidth) + (options.spaceWidth) * .5; }
                ctx.globalAlpha = 1;
                filteredData.each(function (val, arr, i) {
                    var x = getVolumeX(i);
                    var y = getVolumeY(val.volume);
                    ctx.beginPath();
                    ctx.rect(x, y, options.barWidth, volumeRegion.height / maxVolume * val.volume);
                    ctx.fillStyle = val.close > val.open ? riseColor : fallColor;
                    ctx.fill();
                });

                //画y轴
                var volumeLevel;
                var volumeUnit;
                if (maxVolume < 10000 * 100) {
                    volumeLevel = 10000;
                    volumeUnit = '万';
                }
                else {
                    volumeLevel = 10000 * 100;
                    volumeUnit = '百万';
                }

                var volumeScalers = [];
                volumeScalers.push((maxVolume / volumeLevel).toFixed(2));
                volumeScalers.push((maxVolume / 2 / volumeLevel).toFixed(2));
                volumeScalers.push(volumeUnit);
                var volumeScalerOptions = volumeOptions.yAxis;
                volumeScalerOptions.region = volumeScalerOptions.region || { x: 0 - volumeRegion.x, y: -3, width: volumeRegion.x - 3, height: volumeRegion.height };
                var volumeScalerImp = new yAxis(volumeScalerOptions);
                var volumeScalerPainter = new Painter(this.canvas.id, volumeScalerImp, volumeScalers);
                volumeScalerPainter.paint();
                ctx.restore();
                ctx.save();
            },
            onOrentationChanged: function (e) {
                var orientation = window.orientation;
                function getWidth() { return screen.width;/*((orientation == 90 || orientation == -90) ? screen.width : screen.height) - 40; */}
                if (typeof orientation != 'undefined') {
                    setDebugMsg('orientation=' + orientation + ',getWidth=' + getWidth());
                    //if(orientation == 90 || orientation == -90 || orientation == 0){
                    var me = this;
                    var width = getWidth();
                    //var rate = width/me.canvas.width;
                    me.canvas.width = width;
                    var options = me.klOptions;
                    var chartWidth = width - options.chartMargin.left - options.chartMargin.right;
                    me.klOptions.volume.region.width =
                            me.klOptions.priceLine.region.width =
                            me.klOptions.region.width = chartWidth;
                    //方向改变了，要重画controller
                    me.controller = null;
                    me.hasPaintPriceLine = false;
                    console.log("开2=");
                    drawKL({ start: me.dataRanges.start, to: me.dataRanges.to });
                    // }
                }
            }
        };
        
        
        var initialWidth = Math.min(screen.width,1024)-40;
      


        
        function drawKL(ranges) {         
        	 var maxTime=0; //记录当前显示x轴最大时间值
 			 
             var divW=screen.availWidth;
             var divH=divW*0.65;
               
             document.getElementById("canvasKL").setAttribute("width", divW);
             document.getElementById("canvasKL").setAttribute("height", divH);
        
  		     var rateH=(divH)/390;  //高 放大倍数
			 var rateW=(divW)/1002;  //宽 放大倍数
           
             initialWidth=divW;
             
             //整体边距
             var left_Marg=45.5;
             var top_Marg=Math.max(Math.floor(20.5*rateH)+0.5,15.5);
             var right_Marg=15.5;
             var bottom_Marg=Math.max(Math.floor(15.5*rateH)+0.5,15.5);
             
             var X_AxisH=Math.max(Math.floor(20*rateH),20);//主图与下图之间的X轴坐标H
             
             var volumeRegionBottom=10;//为下部量能柱区的下边间距
             
             
             var HH=divH-(top_Marg+X_AxisH+bottom_Marg); // 390-(20.5+20+19.5)
             
             var volumeRegionH=Math.floor(80*HH/250);  
     
             var MregionH=HH-volumeRegionH;//250; 
             
/*              
             console.log("left_Marg="+left_Marg);
             console.log("top_Marg="+top_Marg);
             console.log("right_Marg="+right_Marg);
             console.log("bottom_Marg="+bottom_Marg);
             console.log("right_Marg="+right_Marg);
             console.log("bottom_Marg="+bottom_Marg);
             
             console.log("X_AxisH="+X_AxisH);
             console.log("HH="+HH);
             
             console.log("MregionH="+MregionH);
             console.log("volumeRegionH="+volumeRegionH); */
             
             //为保证两竖线之间蜡烛钱为恒定6个，需要计算动态设定  barWidth spaceWidth值
             var verticalLineCount=6;
             var w=initialWidth - left_Marg - right_Marg; //实际有效画布大小宽
             
             var num=(verticalLineCount+1)*6+1;//蜡烛数
             var barWidthAndspaceWidth=(1.0*w)/(1.0*num);
             var barWidth=Math.ceil(barWidthAndspaceWidth/2);
             var spaceWidth=barWidthAndspaceWidth-barWidth;
             
             var volumeRegionY=MregionH+top_Marg+X_AxisH; //250+20.5=290.5
             var priceLineY=volumeRegionY+volumeRegionH+volumeRegionBottom; 
             var kOptions = {
                backgroundColor:'#fff',
                riseColor: 'red',
                fallColor: 'green',
                normalColor: 'black',
                //主图区域的边距
                chartMargin:{left:left_Marg,top:top_Marg,right:right_Marg},
                TopText:{
                    font: '9px 宋体', // region: { },
                    color: 'black',
                    align: 'left',
                    fontHeight: 6,
                    textBaseline: 'top'},
                region: { x: left_Marg, y: top_Marg, width: initialWidth - left_Marg - right_Marg, height: MregionH },
                barWidth: barWidth, spaceWidth: spaceWidth, horizontalLineCount: 7, verticalLineCount: verticalLineCount, lineStyle: 'solid', borderColor: 'gray', splitLineColor: '#eeeeee', lineWidth: 1,
                MAs: [ //曲线
                    { color: 'rgb(13,77,240)', daysCount: 5 }, //5日线
                    { color: 'rgb(227,150,34)', daysCount: 10 }, //10日线
                    { color: 'rgb(255,70,251)', daysCount: 20 }, //20日线
                    { color: 'rgb(4,226,24)', daysCount: 30 }  //30日线  改为里面的30数字，可以变成其它的多少日线，还可设定线的颜色
                    ],
                yAxis: { //Y轴(左侧) 价格  刻度值会随着数据变化自动适配，但刻度线的条数一定的（可设置）
                    font: '9px Arial', // region: { },
                    color: 'black',
                    align: 'right',
                    fontHeight: 8,
                    textBaseline: 'top'
                },
                xAxis: { //X轴  时间  刻度值会随着数据变化自动适配，但刻度线的条数一定的（可设置）
                    font: '9px Arial', // region: { },
                    color: 'black',
                    align: 'right',
                    fontHeight: 8,
                    textBaseline: 'top',
                    scalerCount: verticalLineCount+2
                },
                volume: {  //下部能量柱
                    region: { x: left_Marg, y: volumeRegionY, height: volumeRegionH, width: initialWidth - left_Marg - right_Marg },
                    horizontalLineCount: 1,
                    yAxis: {
                        font: '9px Arial', // region: { },
                        color: 'black',
                        align: 'right',
                        fontHeight: 8,
                        textBaseline: 'top'
                    }
                },
                priceLine: {
                    region:{ x: left_Marg, y: priceLineY, height: 60, width: initialWidth - left_Marg - right_Marg },
                    verticalLineCount: 7,
                    horizontalLineCount: 1, lineStyle: 'solid', borderColor: 'gray', splitLineColor: '#eeeeee',fillColor:'lightgray',alpha:.5,
                    yAxis: {
                        font: '9px Arial', // region: { },
                        color: 'black',
                        align: 'right',
                        fontHeight: 8,
                        textBaseline: 'top'
                    }
                },
                controller:{
                    bar: { width: 20, height: 35, borderColor: 'black', fillColor: 'lightgray' },
                    minBarDistance: 20
                }
               
            };
           /*
            if(!painter){            
                var canvas = $id('canvasKL');
                if(canvas.width != initialWidth) canvas.width = initialWidth;
                kl = new kLine(kOptions);
                Kdata = getKLData();
                painter = new Painter('canvasKL', kl, Kdata);
            }
            
            else
            {
            	painter = new Painter('canvasKL', kl, Kdata);
            }
            */
            
           if(!painter){            
                var canvas = $id('canvasKL');
                if(canvas.width != initialWidth) canvas.width = initialWidth;
                var kl = new kLine(kOptions);
                Kdata = getKLData(kOptions.xAxis.scalerCount);
                painter = new Painter('canvasKL', kl, Kdata);
            }
            
            painter.dataRanges = ranges;
            painter.paint();
        }

    </script>


    
</head>
<body  >
    <canvas id="canvasKL" width="600" height="435" style="z-index: 2; border: 1px solid #69c">
        <p>hey,您的浏览器不支持html5，换个浏览器吧，比如google chrome，firefox</p>
    </canvas>
    <div id="debug"></div>

</body>
</html>
